#!/usr/bin/python3
# -*- coding: utf8 -*-
# Date   : 2021/07/21
# Author : Kwan
# Email  : allenxian@live.com
# Blog   : https://my.oschina.net/u/4173440

import string
from time import sleep
from threading import Thread
from queue import Queue
from random import choice
from project.define import dev_logger
from project.service.demo import VehiclesDemo


# 入场队列
EntranceQ = Queue()
# 离场队列
ExitQ = Queue()
# 识别触发
TriggerQ = Queue()


class GateService:
    def __init__(self, **kwargs) -> None:
        self.GateID = kwargs.get('GateID')
        self.GateType = kwargs.get('GateType')
        self.GateName = kwargs.get('GateName')
        self.GateMethods = kwargs.get('GateMethods')
        self.Position = kwargs.get('Position')
        self.GateAddr = kwargs.get('GateAddr')
        self.GateGroup = kwargs.get('GateGroup')
        self.Board = kwargs.get('Board')
        self.Version = kwargs.get('Version')
        # 状态
        self.VehicleType = ""
        self.LicensePlate = ""
        self.LicensePlateImg = ""
        self.TicketNumber = ""
        self.CardNumber = ""
        self.GateTime = ""
        self.GateReady = True
        # 温度检测
        self.GateTemp = 0
        # 数据缓存
        self.CameraData = dict()
        self.Debug = True
        # 测试时租
        self.__demo_hourly_items = VehiclesDemo['Hourly']
        # 测试月租
        self.__demo_monthly_items = VehiclesDemo['Monthly']

    def snapshot(self):
        """
        状态
        """
        return {
            "GateID": self.GateID,
            "GateType":self.GateType,
            "GateName":self.GateName,
            "VehicleType":self.VehicleType,
            "LicensePlate":self.LicensePlate,
            "LicensePlateImg":self.LicensePlateImg,
            "TicketNumber":self.TicketNumber,
            "CardNumber":self.CardNumber,
            "GateTime":self.GateTime,
            "GateReady":self.GateReady,
            "GateTemp":self.GateTemp,
        }

    def generate_card_number(self):
        """
        生成卡号
        """
        num_len = 10
        card_number = []
        num_str = string.digits
        while num_len:
            card_number.append(choice(num_str))
            num_len -= 1
        card = "".join(card_number)
        if card != self.CardNumber:
            self.CardNumber = card
            dev_logger.debug(f"闸机名称：{self.GateName} 拍卡成功 => {self.CardNumber}")

    def generate_ticket_number(self):
        """
        生成票号
        """
        ticket_len = 10
        ticket_number = []
        ticket_str = string.ascii_letters + string.digits
        while ticket_len:
            ticket_number.append(choice(ticket_str))
            ticket_len -= 1
        ticket = "".join(ticket_number)
        if ticket != self.TicketNumber:
            self.TicketNumber = ticket
            dev_logger.debug(f"闸机名称：{self.GateName} 出票成功 => {self.TicketNumber}")

    def generate_temperature(self):
        """
        生成温度
        """
        demo = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]
        temp = float(choice(range(36,40))) + choice(demo)
        if temp != self.GateTemp:
            self.GateTemp = temp
            dev_logger.debug(f"闸机名称：{self.GateName} 温度变化 => {self.GateTemp}")

    def gate_upbar_event(self, **kwargs):
        """
        起杆事件
        """
        msg = f"闸机名称：{self.GateName} 起杆信号 => 来源：{kwargs.get('ServerName')} 车型：{kwargs.get('VehicleType')} 车牌：{kwargs.get('LicensePlate')}"
        dev_logger.debug(msg)
        self.GateReady = False
        self.TicketNumber = ""
        self.CardNumber = ""

    def vehicle_type_detect_task(self):
        """
        车型检测
        """
        dev_logger.debug(f"闸机名称：{self.GateName} 开始检测车型")
        while True:
            if self.Debug:
                vehicle_type = choice(["Car","Moto","Barrier",""])
                if vehicle_type != self.VehicleType:
                    self.VehicleType = vehicle_type
                    dev_logger.debug(f"{self.GateName} 地感信号变化 => {self.VehicleType}")
                    # 准备状态
                    if not self.GateReady:
                        if self.VehicleType in ("Barrier", ""):
                            self.GateReady = True
                            dev_logger.debug(f"{self.GateName} 准备信号变化 => {self.GateReady}")
                    # 清空信息
                    if vehicle_type == "":
                        self.TicketNumber = ""
                        self.CardNumber = ""
                    # 触发识别
                    if vehicle_type in ("Car", "Moto"):
                        dev_logger.debug(f"{self.GateName} 车辆检测 => {vehicle_type}")
                        TriggerQ.put(self.snapshot())
            sleep(choice(range(5,10)))

    def licenseplate_result_trigger(self, **kwargs):
        """
        演示测试
        """
        try:
            dev_logger.debug(f"识别信息 => {kwargs}")
            # 更新数据
            self.CameraData = kwargs.copy()
            self.__dict__.update(**kwargs)
            # 演示数据
            demo = None
            for i in (self.__demo_hourly_items, self.__demo_monthly_items):
                for c in i:
                    if self.LicensePlate == c['LicensePlate']:
                        demo = c
                        break
            if not demo:
                # 时租取票
                if "Ticket" in self.GateMethods:
                    if self.TicketNumber == "" and self.CardNumber == "":
                        if choice(range(2)):
                            self.generate_ticket_number()
                # 月租刷卡
                if "Card" in self.GateMethods:
                    if self.CardNumber == "" and self.TicketNumber == "":
                        if choice(range(2)):
                            self.generate_card_number()
            else:
                self.__dict__.update(**demo)
            if "Temp" in self.GateMethods:
                self.generate_temperature()
            ret = self.snapshot()
            if self.GateType == "Entrance":
                EntranceQ.put(ret)
            elif self.GateType == "Exit":
                ExitQ.put(ret)
        except Exception as e:
            dev_logger.error(f"闸机处理错误！原因：{e}")

    def service_init(self):
        """
        服务初始化
        """
        vehicle_detect_t = Thread(target=self.vehicle_type_detect_task, daemon=True)
        vehicle_detect_t.start()

